package come.demo.widgets;

import android.support.v7.widget.RecyclerView;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/11/29.
 */

public abstract class BaseRecyclerAdapter<T, VH extends BaseRecyclerAdapter.BaseViewHolder> extends RecyclerView.Adapter<VH> {

    List<T> mData;
    private boolean mLastDataIsError = false;
    public BaseRecyclerAdapter(List<T> data) {
        mData = data;
    }

    public void checkDataIsError(List<T> data) {
        mLastDataIsError = data == null;
    }

    public void checkDataIsError(T[] data) {
        mLastDataIsError = data == null;
    }

    public boolean isLastError() {
        return mLastDataIsError;
    }


    public void refreshDatas(List<T> data) {
        checkDataIsError(data);
        mData = data;
        if (mData == null) {
            mData = new ArrayList<>();
        }
        notifyDataSetChanged();
    }


    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    public void setOnItemCLKListener(OnItemCLKListener onItemCLKListener) {
        this.mOnItemCLKListener = onItemCLKListener;
    }

    public T getItem(int position) {
        if (mData == null)
            return null;
        else
            return position < 0 ? null : position >= mData.size() ? null : mData.get(position);
    }

    protected OnItemCLKListener mOnItemCLKListener;

    public interface OnItemCLKListener {
        void onItemClick(View view, BaseRecyclerAdapter adapter, int position);
    }


    public class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public BaseViewHolder(View itemView) {
            super(itemView);
        }

        public void setClickListener(View view) {
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (mOnItemCLKListener != null) {
                mOnItemCLKListener.onItemClick(v, BaseRecyclerAdapter.this, getAdapterPosition());
            }
        }
    }

}
